package com.my12306.common.config.quartz;

import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @Author:苏牧夕
 * @Date:2020/5/27 16:23
 * @Version 1.0
 */
@Configuration
public class JobConfig {
    @Autowired
    private JobFactory jobFactory;
    @Autowired
    private DataSource dataSource;

    /**
     * 任务调度负责注册控制实例化bean的工厂
     *
     * @return
     */
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() {
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        schedulerFactoryBean.setJobFactory(jobFactory);
        //启动时是否更新已经存在的job(任务调度)
        schedulerFactoryBean.setOverwriteExistingJobs(true);
        //延迟启动
        schedulerFactoryBean.setStartupDelay(0);
        //设置加载配置文件来加载quartz的属性
//        schedulerFactoryBean.setConfigLocation(new ClassPathResource("配置文件的位置"));
        //通过代码配置来设置quartz的属性
        Properties properties = new Properties();
        //设置调度实例名字
        properties.put("org.quartz.scheduler.instanceName", "health-ilife");
        //实例instanceID设置尾AuTO
        properties.put("org.quartz.scheduler.instanceId", "AUTO");
        //设置任务调度使用的线程池，使用quartz内部提供的线程池
        properties.put("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool");
        //设置总线程数
        properties.put("org.quartz.threadPool.threadCount", "10");
        //设置线程优先级
        properties.put("org.quartz.threadPool.threadPriority", "5");
        //是否是经常上下文的类加载器的线程，默认是true
        properties.put("org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread", true);

        //配置quartz的存储方式使用JobStoreTx 即数据库做持久化
        //org.quartz.simpl.RAMJobStore 默认使用的是内存存储
        properties.put("org.quartz.jobStore.class", "org.quartz.impl.jdbcjobstore.JobStoreTX");
        properties.put("org.quartz.jobStore.driverDelegateClass", "org.quartz.impl.jdbcjobstore.StdJDBCDelegate");
//        org.quartz.jobStore.dataSource = myDS
        properties.put("org.quartz.jobStore.isClustered", true);
        //应该是心跳检测时间
        properties.put("org.quartz.jobStore.clusterCheckinInterval", "20000");
        //官方提供的数据库表的前缀是QRTZ_
        properties.put("org.quartz.jobStore.tablePrefix", "QRTZ_");
        schedulerFactoryBean.setQuartzProperties(properties);
        //自动启动
        schedulerFactoryBean.setAutoStartup(true);
        schedulerFactoryBean.setDataSource(dataSource);
        return schedulerFactoryBean;
    }

    /**
     * 注册一个调度器
     *
     * @return
     */
    @Bean("scheduler")
    public Scheduler scheduler() {
        return schedulerFactoryBean().getScheduler();
    }
}
